package com.yztstudy.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yztstudy.dto.Result;
import com.yztstudy.entity.Shop;
import com.yztstudy.mapper.ShopMapper;
import com.yztstudy.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yztstudy.utils.CacheClient;
import com.yztstudy.utils.RedisConstants;
import com.yztstudy.utils.RedisData;
import com.yztstudy.utils.SystemConstants;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10); //重建缓存的线程池

    /**
     * TODO 根据id查询商铺信息
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {

        //TODO 1.解决缓存击穿
        // Shop shop = queryWithMutex(id); //使用互斥锁
        // Shop shop = queryWithLogicalExpire(id); //使用逻辑删除

        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES); //解决的是缓存穿透的问题
        if (shop == null)
        {
            return Result.fail("店铺不存在!");
        }

        //TODO 2.返回结果给表示层
        return Result.ok(shop);
    }


    /**
     * TODO 根据ID查询店铺,利用了逻辑延时,相当于是持久化高热度的key
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id)
    {
        // TODO 1.先从redis中查询用户是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        // TODO 2.判断是否存在，不存在就直接返回
        if (StrUtil.isBlank(shopJson)) //没有命中有效值
        {
            return null;
        }

        // TODO 3.如果命中，把JSON反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class); //获取店铺对象
        LocalDateTime expireTime = redisData.getExpireTime(); //获取过期时间

        // TODO 4.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) //如果没有过期
        {
            return shop;
        }

        // TODO 5.如果过期了,重新构建缓存
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Boolean isLock = tryLock(lockKey);
        if (isLock) //如果获取锁成功
        {
            CACHE_REBUILD_EXECUTOR.submit(() -> {

                try {
                    this.saveShop2Redis(id, 20L); //查询数据库，重写缓存
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    unLock(lockKey); //释放锁
                }

            });
        }

        // TODO 6.如果获取锁失败，就返回旧的数据
        return shop;
    }


    /**
     * TODO 根据ID查询店铺,利用了互斥锁,相当于是同一时间段，只有一个用户访问数据库服务器
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id)
    {
        // TODO 1.先从redis中查询用户是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        // TODO 2.判断是否存在，存在就直接返回
        if (StrUtil.isNotBlank(shopJson)) //有商铺数据才返回true
        {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // TODO 3.判断是否命中了空值
        if (shopJson != null) //命中空值,即shopJson= ""
        {
            return null;
        }

        // TODO 4.不存在就从数据库查询
        String lockKey = RedisConstants.CACHE_SHOP_KEY + id;
        Shop shop = null;
        try {
            //4.1 尝试获取互斥锁
            Boolean isLock = tryLock(lockKey);

            //4.2失败，休眠，重新尝试
            if (!isLock)
            {
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            //4.4成功，查询数据库
            shop = getById(id);

            //4.5 数据库没有，就写空值
            if (shop == null)
            {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "");
                stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES); //设置过期时间
                return null;
            }

            //4.6 数据库存在就写入redis，同时给前端
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop));
            stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES); //设置过期时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //4.7释放互斥锁
            unLock(lockKey);

            return shop;
        }
    }


    /**
     * TODO 根据ID查询店铺,没有使用防止缓存击穿的手段
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id)
    {
        // TODO 1.先从redis中查询用户是否存在
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        // TODO 2.判断是否存在，存在就直接返回
        if (StrUtil.isNotBlank(shopJson)) //有商铺数据才返回true
        {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // TODO 3.判断是否命中了空值
        if (shopJson != null) //命中空值
        {
            return null;
        }

        // TODO 4.不存在就从数据库查询
        Shop shop = getById(id);

        // TODO 5.数据库也不存在，使用防止缓存穿透的手段，记录空值
        if (shop == null)
        {
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "");
            stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES); //设置过期时间
            return null;
        }

        // TODO 6.存在就写入redis，同时给前端
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop));
        stringRedisTemplate.expire(RedisConstants.CACHE_SHOP_KEY + id, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES); //设置过期时间
        return shop;
    }


    /**
     * TODO 尝试获取锁
     * @param key key值
     * @return
     */
    private Boolean tryLock(String key)
    {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);

        return BooleanUtil.isTrue(flag); //是否能返回true
    }


    /**
     * TODO 尝试释放锁
     * @param key key值
     * @return
     */
    private void unLock(String key)
    {
        stringRedisTemplate.delete(key);
    }


    /**
     * TODO 把Shop存在Redis中
     */
    public void saveShop2Redis(Long id, Long expireSecond)
    {
        // TODO 1.查询店铺数据
        Shop shop = getById(id);

        // TODO 2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond)); //延长过期时间

        // TODO 3.导入Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    /**
     * TODO 根据id更新店铺
     * @param shop 店铺对象
     * @return
     */
    @Transactional
    @Override
    public Result update(Shop shop) {

        Long id = shop.getId();
        if (id == null)
        {
            return Result.fail("店铺ID不能为空");
        }

        // TODO 1.更新数据库
        updateById(shop);

        // TODO 2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);

        return Result.ok();
    }


    /**
     * TODO 根据商铺类型分页查询商铺信息
     * @param typeId 商铺类型
     * @param current 页码
     * @param x 经度
     * @param y 纬度
     * @return
     */
    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {

        // TODO 1.判断是否需要进行坐标查询
        if (x == null || y == null) //不需要，就行数据库查询
        {
            Page<Shop> page = query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        // TODO 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE; //起始的标记
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE; //终止的标记

        // TODO 3.查询Redis，按照距离进行排序，分页。结果: shopId, distance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        Circle circle = new Circle(new Point(x, y), 5000);
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().radius(key, circle, RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));

        if (results == null) //没有任何店铺。返回一个空的集合
        {
            return Result.ok(Collections.emptyList());
        }

        // TODO 4.解析出shopId和distance
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from)
        {
            return Result.ok(Collections.emptyList());
        }

        List<Long> ids = new ArrayList<>(list.size()); //保存这个所有的店铺Id
        Map<String, Distance> distanceMap = new HashMap<>(list.size()); //保存每个店铺的距离
        list.stream().skip(from).forEach(result -> {
            String shopIdStr = result.getContent().getName(); //shopId
            ids.add(Long.valueOf(shopIdStr));

            Distance distance = result.getDistance(); //distance
            distanceMap.put(shopIdStr, distance);
        });

        // TODO 5.根据id查询店铺
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id, " + idStr + ")").list();
        for (Shop shop : shops)
        {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        return Result.ok(shops);
    }


    /**
     * TODO 根据商铺的名字来分页查询商铺的信息
     * @param name 商铺的名字
     * @param current 页码
     * @return
     */
    @Override
    public Result queryShopByName(String name, Integer current) {
        // TODO 1.根据类型分页查询
        Page<Shop> page = query().like(StrUtil.isNotBlank(name), "name", name).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));

        // TODO 2. 返回数据
        return Result.ok(page.getRecords());
    }


    /**
     * TODO 新增店铺
     * @param shop 店铺对象
     * @return
     */
    @Override
    public Result saveShop(Shop shop) {
        // TODO 1.写入数据库
        save(shop);

        // TODO 2.返回店铺ID
        return Result.ok(shop.getId());
    }
}
